<template>
	<view class="cart-item-container">
		<view class="cart-item" :class="{ checked: item.checked }">
			<!-- 上部区域：复选框、图片、信息 -->
			<view class="item-top">
				<!-- 复选框 -->
				<view class="checkbox-wrapper" v-if="showCheckbox" @tap.stop>
					<cl-checkbox round v-model="item.checked" active-color="#667eea" />
				</view>

				<!-- 商品图片 -->
				<view class="product-image">
					<goods-cover :size="180" :item="item.goodsInfo" />
					<!-- 处方药标签 -->
					<view v-if="item.goodsInfo.isPres === 1" class="rx-badge"> Rx </view>
					<!-- 缺货遮罩 -->
					<view v-if="item.goodsInfo.storNum === 0" class="out-of-stock">
						<text>缺货</text>
					</view>
				</view>

				<!-- 商品信息 -->
				<view class="product-info">
					<view class="info-main">
						<!-- 标题 -->
						<text class="product-title">{{ item.goodsInfo.title }}</text>
						<!-- 规格 -->
						<text class="product-spec">规格: {{ item.goodsInfo.goodsSpec }}</text>
						<!-- 厂家 -->
						<text class="product-manufacturer">{{ item.goodsInfo.manufacturer }}</text>
					</view>

					<!-- 删除按钮 -->
					<view class="delete-btn" @tap.stop="onDelete">
						<cl-icon name="delete" size="20" color="#ff4757" />
					</view>
				</view>
			</view>

			<!-- 中部区域：标签 -->
			<view class="item-middle">
				<!-- 包装标签 -->
				<view class="tag" v-if="item.goodsInfo.midpack && item.goodsInfo.midpack > 1">
					<text class="tag-text"
						>中包装{{ item.goodsInfo.midpack }}{{ item.goodsInfo.unit }}</text
					>
				</view>
				<view class="tag success" v-if="item.goodsInfo.isMidpackSaleDisabled === 0">
					<text class="tag-text">可拆零</text>
				</view>
				<view
					class="tag warning"
					v-else-if="item.goodsInfo.midpack && item.goodsInfo.midpack > 1"
				>
					<text class="tag-text">{{ item.goodsInfo.midpack }}倍数</text>
				</view>
				<!-- 近效期 -->
				<view class="tag danger" v-if="item.goodsInfo.nearestExpiredDate">
					<text class="tag-text"
						>效期: {{ formatDate(item.goodsInfo.nearestExpiredDate) }}</text
					>
				</view>
			</view>

			<!-- 底部区域：价格和数量 -->
			<view class="item-bottom">
				<view class="price-section">
					<view class="price-wrapper" v-if="user.token">
						<view class="price-main">
							<text class="price">{{
								formatUserPrice(
									item.goodsInfo.price,
									user,
									item.goodsInfo.noDiscounts
								)
							}}</text>
						</view>
						<view class="original-price" v-if="hasDiscount">
							{{ formatUserPrice(item.goodsInfo.price, user, 1) }}
						</view>
					</view>
					<view class="price-wrapper" v-else>
						<text class="login-tip">登录查看价格</text>
					</view>
					<view class="stock-info" :class="getStockClass(item.goodsInfo.storNum)">
						<text>库存{{ getStockText(item.goodsInfo.storNum) }}</text>
					</view>
				</view>

				<!-- 数量控制 -->
				<view class="quantity-wrapper">
					<view class="quantity-stepper">
						<view
							class="stepper-btn minus"
							@tap="decreaseQuantity"
							:class="{ disabled: item.count <= getMinQuantity(item.goodsInfo) }"
						>
							<text>−</text>
						</view>
						<input
							class="stepper-input"
							type="number"
							v-model="item.count"
							@blur="onQuantityBlur"
						/>
						<view
							class="stepper-btn plus"
							@tap="increaseQuantity"
							:class="{ disabled: item.count >= item.goodsInfo.storNum }"
						>
							<text>+</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { type PropType, computed } from "vue";
import { useShoppingCart, type OrderGoods } from "/@/hooks/shopping-cart";
import { formatUserPrice } from "/@/utils/price";
import { useStore } from "/@/cool/store";
import GoodsCover from "./cover.vue";

const props = defineProps({
	item: {
		type: Object as PropType<OrderGoods>,
		required: true,
	},
	showCheckbox: {
		type: Boolean,
		default: true,
	},
});

const emit = defineEmits(["delete", "quantityChange"]);

const spCart = useShoppingCart();
const { user } = useStore();

// 计算是否有折扣
const hasDiscount = computed(() => {
	return (
		user.token &&
		user.info?.discount &&
		user.info.discount < 1 &&
		props.item.goodsInfo.noDiscounts !== 1
	);
});

// 格式化日期
function formatDate(date: string | Date): string {
	if (!date) return "";

	try {
		const d = new Date(date);
		if (isNaN(d.getTime())) return "";

		const year = d.getFullYear();
		const month = String(d.getMonth() + 1).padStart(2, "0");
		const day = String(d.getDate()).padStart(2, "0");

		return `${year}-${month}-${day}`;
	} catch (error) {
		return "";
	}
}

// 获取库存状态文本
function getStockText(storNum: number | undefined): string {
	const stock = Number(storNum || 0);
	if (stock === 0) return "缺货";
	if (stock < 10) return "紧张";
	return "充足";
}

// 获取库存状态样式类
function getStockClass(storNum: number | undefined): string {
	const stock = Number(storNum || 0);
	if (stock === 0) return "out-of-stock";
	if (stock < 10) return "low-stock";
	return "in-stock";
}

// 获取最小数量
function getMinQuantity(goods: any): number {
	return spCart.getMinQuantity(goods);
}

// 获取数量步长
function getQuantityStep(goods: any): number {
	return spCart.getQuantityStep(goods);
}

// 删除按钮点击
function onDelete() {
	emit("delete", props.item);
}

// 数量变化处理
function onQuantityChange(value: number) {
	emit("quantityChange", props.item, value);
}

// 增加数量
function increaseQuantity() {
	const step = getQuantityStep(props.item.goodsInfo);
	const newValue = props.item.count + step;
	if (newValue <= props.item.goodsInfo.storNum) {
		props.item.count = newValue;
		onQuantityChange(newValue);
	}
}

// 减少数量
function decreaseQuantity() {
	const step = getQuantityStep(props.item.goodsInfo);
	const min = getMinQuantity(props.item.goodsInfo);
	const newValue = props.item.count - step;
	if (newValue >= min) {
		props.item.count = newValue;
		onQuantityChange(newValue);
	}
}

// 输入框失去焦点
function onQuantityBlur() {
	const value = Number(props.item.count);
	const min = getMinQuantity(props.item.goodsInfo);
	const max = props.item.goodsInfo.storNum;
	const step = getQuantityStep(props.item.goodsInfo);

	// 验证并调整值
	let adjustedValue = value;
	if (value < min) {
		adjustedValue = min;
	} else if (value > max) {
		adjustedValue = max;
	} else if (step > 1 && value % step !== 0) {
		// 调整为最近的有效倍数
		adjustedValue = Math.round(value / step) * step;
	}

	if (adjustedValue !== value) {
		props.item.count = adjustedValue;
		onQuantityChange(adjustedValue);
	}
}
</script>

<style lang="scss" scoped>
.cart-item-container {
	margin-bottom: 20rpx;
	padding: 0 20rpx;
}

.cart-item {
	background: #ffffff;
	border-radius: 24rpx;
	padding: 24rpx;
	box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
	transition: all 0.3s ease;

	&.checked {
		background: linear-gradient(135deg, #f8f9ff 0%, #f3f4ff 100%);
		box-shadow: 0 6rpx 24rpx rgba(102, 126, 234, 0.12);
		transform: translateY(-2rpx);
	}
}

// 上部区域
.item-top {
	display: flex;
	align-items: flex-start;
	gap: 20rpx;
	margin-bottom: 16rpx;
}

.checkbox-wrapper {
	display: flex;
	align-items: center;
	justify-content: center;
	padding-top: 60rpx;
}

.product-image {
	position: relative;
	width: 180rpx;
	height: 180rpx;
	flex-shrink: 0;
	border-radius: 16rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);

	.rx-badge {
		position: absolute;
		top: 0;
		right: 0;
		background: linear-gradient(135deg, #ff6b6b 0%, #ff4757 100%);
		color: #ffffff;
		font-size: 22rpx;
		font-weight: 700;
		padding: 6rpx 16rpx;
		border-radius: 0 16rpx 0 20rpx;
		box-shadow: 0 4rpx 8rpx rgba(255, 71, 87, 0.3);
	}

	.out-of-stock {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.7);
		display: flex;
		align-items: center;
		justify-content: center;

		text {
			color: #ffffff;
			font-size: 32rpx;
			font-weight: 600;
			padding: 12rpx 28rpx;
			background: rgba(0, 0, 0, 0.9);
			border-radius: 40rpx;
		}
	}
}

.product-info {
	flex: 1;
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	min-width: 0;
}

.info-main {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	padding-right: 16rpx;

	.product-title {
		font-size: 30rpx;
		color: #1a1a1a;
		font-weight: 500;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
	}

	.product-spec {
		font-size: 26rpx;
		color: #666;
	}

	.product-manufacturer {
		font-size: 24rpx;
		color: #999;
	}
}

.delete-btn {
	width: 48rpx;
	height: 48rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	background: #fff3f3;
	transition: all 0.2s ease;

	&:active {
		background: #ffe0e0;
		transform: scale(0.9);
	}
}

// 中部区域 - 标签
.item-middle {
	display: flex;
	flex-wrap: wrap;
	gap: 12rpx;
	margin-bottom: 20rpx;
}

.tag {
	display: inline-flex;
	align-items: center;
	padding: 6rpx 16rpx;
	background: #f0f9ff;
	border-radius: 20rpx;
	border: 1rpx solid #bae6fd;

	.tag-text {
		font-size: 24rpx;
		color: #0284c7;
	}

	&.success {
		background: #f0fdf4;
		border-color: #bbf7d0;
		.tag-text {
			color: #16a34a;
		}
	}

	&.warning {
		background: #fef3c7;
		border-color: #fde68a;
		.tag-text {
			color: #d97706;
		}
	}

	&.danger {
		background: #fee2e2;
		border-color: #fecaca;
		.tag-text {
			color: #dc2626;
		}
	}
}

// 底部区域
.item-bottom {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.price-section {
	display: flex;
	flex-direction: column;
	gap: 8rpx;

	.price-wrapper {
		display: flex;
		flex-direction: column;
		gap: 4rpx;
	}

	.price-main {
		display: flex;
		align-items: baseline;

		.price {
			font-size: 36rpx;
			color: #ff4757;
			font-weight: 600;
		}
	}

	.original-price {
		font-size: 26rpx;
		color: #999;
		text-decoration: line-through;
	}

	.login-tip {
		font-size: 26rpx;
		color: #ff6b6b;
		font-weight: 500;
	}

	.stock-info {
		font-size: 24rpx;
		padding: 4rpx 12rpx;
		border-radius: 20rpx;
		background: #f8f9fa;

		&.in-stock {
			color: #16a34a;
			background: #f0fdf4;
		}

		&.low-stock {
			color: #d97706;
			background: #fef3c7;
		}

		&.out-of-stock {
			color: #dc2626;
			background: #fee2e2;
		}
	}
}

.quantity-wrapper {
	display: flex;
	align-items: center;
}

.quantity-stepper {
	display: flex;
	align-items: center;
	background: #f8f9fa;
	border-radius: 40rpx;
	padding: 6rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);

	.stepper-btn {
		width: 64rpx;
		height: 64rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		transition: all 0.2s ease;
		font-size: 32rpx;
		font-weight: 500;

		&.minus {
			background: #ffffff;
			color: #666;
			box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.08);

			&:active:not(.disabled) {
				transform: scale(0.9);
				background: #f5f5f5;
			}

			&.disabled {
				opacity: 0.3;
				pointer-events: none;
			}
		}

		&.plus {
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
			color: #ffffff;
			box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.3);

			&:active:not(.disabled) {
				transform: scale(0.9);
			}

			&.disabled {
				opacity: 0.5;
				pointer-events: none;
				background: #e0e0e0;
				box-shadow: none;
			}
		}
	}

	.stepper-input {
		min-width: 100rpx;
		max-width: 120rpx;
		text-align: center;
		font-size: 32rpx;
		font-weight: 600;
		color: #1a1a1a;
		background: transparent;
		border: none;
		padding: 0 16rpx;
	}
}
</style>
